﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class Elections : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (!IsPostBack)
            {
                Title = Resources.Resource.Elections_PageTitle + " " + Resources.Resource.Default_PageTitle;

                string CountryId = "", ElectionsId = "";
                if (Request.QueryString["ElectionsId"] != null)
                    ElectionsId = Request.QueryString["ElectionsId"];
                //if (Request.QueryString["National"] != null)
                //    National = Request.QueryString["National"];
                if (Request.QueryString["CountryId"] != null)
                    CountryId = Request.QueryString["CountryId"];
                //else
                //    CountryId = (ou.Country != null) ? ou.Country : "12";

                if (ElectionsId.Length + CountryId.Length <= 0)
                    CountryId = (ou.Country != null) ? ou.Country : "12";

                LanguageIdHiddenField.Value = ou.Language;
                if (ou.UserId != null)
                    UserIdHiddenField.Value = ou.UserId;

                if (ElectionsId == "")
                {
                    ElectionsId = GND.ReadNivdalIntData("CountryId", "Nivdal_ElectionsGetCurrentElectionsInCountry", CountryId);                    
                }
                else if (CountryId == "")
                {
                    CountryId = GND.ReadNivdalIntData("ElectionsId", "Nivdal_ElectionsGetCountryByElectionsId", ElectionsId);
                }

                CountryIdHiddenField.Value = CountryId;
                ElectionsIdHiddenField.Value = ElectionsId;
                
                // at this stage: CountryId is set. Elections Id can be 0 or "", but only if there are no elections in the country
                if ((ElectionsId == "") || (ElectionsId == "0"))
                {
                    GeneralElectionsInfoPanel.Visible = false;
                    NoElectionsInCountryPanel.Visible = true;
                    SignupPanel.Visible = false;
                    PanelCandidate.Visible = false;
                    VotingPanel.Visible = false;
                    ElectionsResultsPanel.Visible = false;
                }
                else 
                {
                    string ElectionsStage = GND.ReadNivdalIntData("ElectionsId", "Nivdal_ElectionsGetStage", ElectionsId);
                    NoElectionsInCountryPanel.Visible = false;
                    SignupPanel.Visible = ((ElectionsStage == "1") && 
                                           GND.ReadNivdalBoolData("ElectionsId", "UserId", "Nivdal_ElectionsCanUserBecomeCandidate", ElectionsId, ou.UserId));
                    
                    PanelCandidate.Visible = ((ElectionsStage == "1" || ElectionsStage == "2") &&
                                               GND.ReadNivdalBoolData("ElectionsId", "UserId", "Nivdal_ElectionsIsUserACandidate", ElectionsId, ou.UserId));
                    VotingPanel.Visible = (ElectionsStage == "2");
                    ElectionsResultsPanel.Visible = (ElectionsStage == "4");
                    
                    LoadVotingPanel();
                }

                if ((ou.UserAccessLevel == "4" || ou.UserAccessLevel == "5") && GeneralElectionsInfoPanel.Visible)
                    CandidatesApprovalPanel.Visible = true;
                else
                    CandidatesApprovalPanel.Visible = false;

                if (ElectionsId != "" && ElectionsId != "0")
                {
                    PendingApprovalDataSource.SelectParameters.Add("ElectionsId", ElectionsId);
                } 
                else
                    PendingApprovalDataSource.SelectParameters.Add("ElectionsId", "0");
                
                PendingApprovalDataSource.SelectParameters.Add("UserAccessLevel", ou.UserAccessLevel);
                AllCandidatesdataSource.SelectParameters.Add("CountryId", ou.Country);
                AllCandidatesdataSource.SelectParameters.Add("UserAccessLevel", ou.UserAccessLevel);

                VotingDataSource.SelectParameters.Add("ElectionsId", ElectionsId);
                if (ou.UserId != null) VotingDataSource.SelectParameters.Add("UserId", ou.UserId);

                OldElectionsPanel.Visible = (OldElectionsGridview.Rows.Count > 0);
            }

           
        }

        protected void GoToOtherelections(object sender, EventArgs e)
        {
            string ElectionsId = (GeneralElectionsInfoFormView.FindControl("OngoingElectionsDDL") as DropDownList).SelectedValue;
            Response.Redirect("~/Elections.aspx?ElectionsId=" + ElectionsId);
        }

        private void  LoadVotingPanel()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"]; 
            
            if (VotingPanel.Visible)
            {
                string VoteForUserId = GND.ReadNivdalStringData("UserId", "ElectionsId", "Nivdal_ElectionsGetUserVote", ou.UserId, ElectionsIdHiddenField.Value);
                if (VoteForUserId.Length > 0)
                {
                    VotedforHyperlink.Text = GND.ReadNivdalStringData("UserId", "Nivdal_GetUserNameById", VoteForUserId);
                    VotedforHyperlink.NavigateUrl = "~/UserPage.aspx?Id=" + VoteForUserId;
                    VotedPanel.Visible = CanVote();
                    string CandidateVoted = GND.ReadNivdalIntData("UserId", "ElectionsId", "Nivdal_ElectionsGetCandidateIdUserVotedFor", ou.UserId, ElectionsIdHiddenField.Value);
                    if (CandidateVoted.Length > 0)
                        CandidatesRadioButtonList.SelectedValue = CandidateVoted;
                }
                else VotedPanel.Visible = false;

                ListOfSpeechesLink.NavigateUrl = "~/ElectionSpeeches.aspx?ElectionsId=" + ElectionsIdHiddenField.Value;

                // if the user cannot vote - remove voting buttons
                if (!CanVote())
                {
                    VoteButton.Visible = false;
                    CandidatesRadioButtonList.Enabled = false;
                }
            }
        }

        protected bool CanVote()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            return GND.ReadNivdalBoolData("ElectionsId", "UserId", "Nivdal_ElectionsCanUserVoteInElections", ElectionsIdHiddenField.Value, ou.UserId);
        }

        protected void SubmitCandidacy(object Sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (GND.ReadNivdalBoolData("UserId", "ElectionsId", "Nivdal_ElectionsCanUserBecomeCandidate", ou.UserId, ElectionsIdHiddenField.Value))
            {
                GND.ExecNivdalSQL("UserId", "ElectionsId", "Speach", "Nivdal_ElectionsSetUserIsACandidate", ou.UserId, ElectionsIdHiddenField.Value, SpeechTextBox.Text.Trim());
                SignupPanel.Visible = false;
                PanelCandidate.Visible = true;
                SpeechTextBox.Text = "";
            }
        }

        protected void WithdrawFromElections(object Sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            GND.ExecNivdalSQL("UserId", "ElectionsId", "Nivdal_ElectionsWithdrawFromElections", ou.UserId, ElectionsIdHiddenField.Value);
            PanelCandidate.Visible = false;

            string ElectionsStage = GND.ReadNivdalIntData("ElectionsId", "Nivdal_ElectionsGetStage", ElectionsIdHiddenField.Value);

            if (ElectionsStage == "1")
            {
                SignupPanel.Visible = true;                
            }
            if (ElectionsStage == "2")
            {
                //CandidatesListview.DataBind();
                CandidatesRadioButtonList.DataBind();
            }


        }

        protected void ApproveSelected(object sender, EventArgs e)
        { 
            // approves all the candidates that are selected
            foreach (GridViewRow r in PendingApprovalGridview.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    string CandidateID = (r.FindControl("CandidateIdHiddenField") as HiddenField).Value;
                    bool Approved = (r.FindControl("ApproveCheckBox") as CheckBox).Checked;

                    if (Approved)
                    {
                        GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                        GND.ExecNivdalSQL("CandidateId", "Nivdal_ElectionsApproveCandidate", CandidateID);
                    }

                }
            }
            PendingApprovalGridview.DataBind();
            AllCandidatesGridview.DataBind();
        }

        protected void Vote(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Vote")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                GND.ExecNivdalSQL("UserId", "ElectionsId", "VoteFor", "Nivdal_ElectionsCastVote", ou.UserId, ElectionsIdHiddenField.Value, e.CommandArgument);
                LoadVotingPanel();
                CandidatesRadioButtonList.DataBind();
                //CandidatesListview.DataBind();
            }
        }

        protected void SubmitVote(object sender, EventArgs e)
        {
            string CandidateId = CandidatesRadioButtonList.SelectedValue;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (CandidateId.Length > 0)
            {
                GND.ExecNivdalSQL("UserId", "ElectionsId", "VoteFor", "Nivdal_ElectionsCastVote", ou.UserId, ElectionsIdHiddenField.Value, CandidateId);
                LoadVotingPanel();
            }

        }
        
        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }
    }
}